package zhan.shiro.filter;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 访问控制过滤器
 *
 */

@Component("myFilter")
public class MyFilter extends AccessControlFilter {

    public static final Logger log = Logger.getLogger(MyFilter.class);
    /**  认证通过要做的操作 */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {

        log.info("访问控制过滤器===========myFilter===========认证被允许的filter");

        if (null != getSubject(servletRequest, servletResponse) && getSubject(servletRequest, servletResponse).isAuthenticated()) {
            return true;
        }
        return false;
    }

    /**  认证被拒绝 要做的操作 ，一般就是跳转到登录页*/
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        log.error("认证被拒！！！！");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Map<String, String[]> parameterMap = request.getParameterMap();
        String[] userName = parameterMap.get("login_name");
        String[] loginPwd = parameterMap.get("login_pwd");


        UsernamePasswordToken token = new UsernamePasswordToken(userName[0], loginPwd[0]);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return true;
        }catch (Exception e){
            log.error("登录失败"+e);
        }
        return false;
    }
}
